/**
 * 转换时间格式
 * @param date 将转换的时间
 * @param fmt 转换成的格式 yyyy-MM-dd|yyyy-MM-dd hh:mm:ss
 * @example 
 * let newDate = '2022-09-06T15:48:27.239+08:00';
 *	let D1 = DateFormat(newDate, 'yyyy-MM-dd');
 *	let D2 = DateFormat(newDate, 'yyyy-MM-dd hh:mm:ss');
 */
const DateFormat = (date, fmt) => {
	if (date && fmt) {
		let _date = new Date(date);
		var o = {
			'M+': _date.getMonth() + 1, //月份
			'd+': _date.getDate(), //日
			'h+': _date.getHours(), //小时
			'm+': _date.getMinutes(), //分
			's+': _date.getSeconds(), //秒
			'q+': Math.floor((_date.getMonth() + 3) / 3), //季度
			S: _date.getMilliseconds(), //毫秒
		};
		if (/(y+)/.test(fmt)) {
			const matchedYear = fmt.match(/(y+)/)[0];
			fmt = fmt.replace(matchedYear, (_date.getFullYear().toString()).slice(-matchedYear.length));
		}
		for (let k in o) {
			if (new RegExp('(' + k + ')').test(fmt)) {
				const match = fmt.match(new RegExp('(' + k + ')'));
				const matchedString = match[0];
				const formattedValue = matchedString.length === 1 ? o[k] : ('00' + o[k]).slice(-matchedString.length);
				fmt = fmt.replace(matchedString, formattedValue);
			}
		}	
		return fmt;
	} else {
		return '';
	}
};
/**  单位换算，格式化显示长度     */
const LengthFormat = (val, unit) =>{
	if (val == null) return "";
	val = Number(val);

	if (unit == null || unit == "auto") {
		if (val < 1000)
			unit = "m";
		else
			unit = "km";
	}
	let valstr = "";
	switch (unit) {
		default:
		case "m":
			valstr = val.toFixed(2) + '米';
			break;
		case "km":
			valstr = (val * 0.001).toFixed(2) + '公里';
			break;
		case "mile":
			valstr = (val * 0.00054).toFixed(2) + '海里';
			break;
		case "zhang":
			valstr = (val * 0.3).toFixed(2) + '丈';
			break;
	}
	return valstr;
}

//格式化时间
const TimeFormat = (strtime) => {
if (strtime < 60)
	return strtime.toFixed(0) + "秒";
else if (strtime >= 60 && strtime < 3600) {
	var miao = Math.floor(strtime % 60);
	return Math.floor(strtime / 60) + "分钟" + (miao != 0 ? (miao + "秒") : "");
} else {
	strtime = Math.floor(strtime / 60); //秒转分钟
	return Math.floor(strtime / 60) + "小时" + Math.floor(strtime % 60) + "分钟";
}
}

export { DateFormat,LengthFormat,TimeFormat }


